import Objects from "../../utils/objects";
import Environment from "../../utils/environment";
/**
 * VisualRoamer 空间距离量测
 * @param viewer Cesium.Viewer
 * @constructor VisualRoamer
 */
function VisualRoamer(viewer) {
    this._viewer = window.cesiumViewer;

    VisualRoamer._HANDLER = new Cesium.ScreenSpaceEventHandler(this._viewer.scene.canvas);

    this._data = [];
    this._positions = [];
    this._distance = [];
    this._distance1 = [];
    this._polyline = null;

    this._height = this._viewer.scene.globe.ellipsoid.cartesianToCartographic(this._viewer.camera.position).height;

    this.setView();
    VisualRoamer.MEASURERS.push(this);
}

VisualRoamer._HANDLER = null;
VisualRoamer.MEASURERS = [];

Object.defineProperties(VisualRoamer.prototype, {
    stopped: {
        get: function() {
            return this._stopped;
        }
    }
});

VisualRoamer.newInstance = function(viewer) {
    return new VisualRoamer(viewer);
};

VisualRoamer.lastMeasurer = function() {
    if (VisualRoamer.MEASURERS.length === 0) {
        throw new Error("尚未拥有实例！！！");
    }
    return VisualRoamer.MEASURERS[VisualRoamer.MEASURERS.length - 1];
};

VisualRoamer.prototype.setView = function() {
    // this._viewer.camera.setView({
    //     destination: Cesium.Cartesian3.fromDegrees(116.405419, 39.918034, 800000),
    //     orientation: new Cesium.HeadingPitchRoll(Cesium.Math.toRadians(0), Cesium.Math.toRadians(-90), Cesium.Math.toRadians(0))
    // });
};

VisualRoamer.prototype.start = function() {
    let that = this;
    // that._viewer.animation.container.style.visibility = "hidden";
    // that._viewer.timeline.container.style.visibility = "hidden";
    VisualRoamer._HANDLER.setInputAction(function(event) {
        let earthPosition = that._getCartesian3FromPosition(event.position, []);
        // earthPosition.z = earthPosition.z + 6500;

        that._positions.push(earthPosition);
        if (that._positions.length === 2) {
            that.creatLine();
        }

        that._distance.push(earthPosition);

        //笛卡尔坐标系（x,y,z）转换成经纬度
        //输入值为cartesian

        let geoPt = that._viewer.scene.globe.ellipsoid.cartesianToCartographic(earthPosition);

        geoPt.longitude = geoPt.longitude * (180.0 / Math.PI);
        geoPt.latitude = geoPt.latitude * (180.0 / Math.PI);

        geoPt.height = 20000;

        that._data.push(geoPt);
        that._data[0].time = 0;
    }, Cesium.ScreenSpaceEventType.LEFT_CLICK);
};

VisualRoamer.prototype.stop = function() {
    let that = this;

    VisualRoamer._HANDLER.removeInputAction(Cesium.ScreenSpaceEventType.LEFT_CLICK);
    VisualRoamer._HANDLER.removeInputAction(Cesium.ScreenSpaceEventType.MOUSE_MOVE);

    for (let i = 1; i < that._distance.length; i++) {
        that._distance1.push(Cesium.Cartesian3.distance(that._distance[i], that._distance[i - 1]));
    }
    //求数组元素之和
    let sum = eval(that._distance1.join("+"));

    for (let i = 1; i < that._distance.length - 1; i++) {
        that._data[i].time = that._data[i - 1].time + (that._distance1[i - 1] / sum) * 360;
    }

    that._data[that._distance.length - 1].time = 360;
};

VisualRoamer.prototype._getCartesian3FromPosition = function(position, ...noPickEntityArray) {
    let that = this;

    let picks = this._viewer.scene.drillPick(position);
    this._viewer.render();

    let getOnModel = false;
    let cartesian3 = null;

    if (this._viewer.scene.pickPositionSupported) {
        for (let i = 0; i < picks.length; i++) {
            let pickedObject = picks[i];
            for (let j = 0; j < noPickEntityArray.length; j++) {
                let noPickEntity = noPickEntityArray[j];
                if (that._hasPickedModel(pickedObject, noPickEntity)) {
                    getOnModel = true;
                }
            }
        }
    }

    if (getOnModel) {
        cartesian3 = this._viewer.scene.pickPosition(position);
    } else {
        let ray = this._viewer.camera.getPickRay(position);
        if (Objects.isNull(ray)) {
            return null;
        }
        cartesian3 = this._viewer.scene.globe.pick(ray, this._viewer.scene);
    }
    return cartesian3;
};

VisualRoamer.prototype.creatLine = function() {
    let that = this;
    that._polyline = that._viewer.entities.add({
        polyline: {
            positions: new Cesium.CallbackProperty(function() {
                return that._positions;
            }, false),
            show: true,
            disableDepthTestDistance: Number.POSITIVE_INFINITY,
            material: Cesium.Color.YELLOW,
            width: 3
            // clampToGround: true,
        }
    });
    return that._polyline;
};

VisualRoamer.prototype.startFly = function() {
    let that = this;
    // that._viewer.animation.container.style.visibility = "visible";
    // that._viewer.timeline.container.style.visibility = "visible";
    //清除绘制的线，展示路径线(因为绘制线和路径线有点区别)
    that._viewer.entities.remove(that._polyline);

    // // 起始时间
    let start = Cesium.JulianDate.fromDate(new Date(2020, 7, 11));
    // 结束时间
    let stop = Cesium.JulianDate.addSeconds(start, 360, new Cesium.JulianDate());

    // 设置始时钟始时间
    that._viewer.clock.startTime = start.clone();
    // 设置时钟当前时间
    that._viewer.clock.currentTime = start.clone();
    // 设置始终停止时间
    that._viewer.clock.stopTime = stop.clone();
    // 时间速率，数字越大时间过的越快
    that._viewer.clock.multiplier = 10;

    // 时间轴
    that._viewer.timeline.zoomTo(start, stop);
    // 循环执行,即为2，到达终止时间，重新从起点时间开始
    that._viewer.clock.clockRange = Cesium.ClockRange.LOOP_STOP;
    that._viewer.clock.shouldAnimate = true;
    let property = that.computeFlight(that._data);
    //console.log(that._data.length);

    if (that._height < 5000000) {
        // 添加模型
        //使得第一视角
        that._viewer.trackedEntity = that._viewer.entities.add({
            // 和时间轴关联
            availability: new Cesium.TimeIntervalCollection([
                new Cesium.TimeInterval({
                    start: start,
                    stop: stop
                })
            ]),
            position: property,
            // 根据所提供的速度计算模型的朝向
            orientation: new Cesium.VelocityOrientationProperty(property),
            // 模型数据
            model: {
                /*  uri:  "feiji.gltf",*/
                uri: Environment.getDataBasePath() + "/file/feiji.gltf",
                scale: 0.1
            },
            path: {
                resolution: 1,
                material: new Cesium.PolylineGlowMaterialProperty({
                    glowPower: 0.1,
                    color: Cesium.Color.YELLOW
                }),
                width: 10
            }
        });
    } else {
        // 添加模型
        //使得第一视角
        that.animateEntity = that._viewer.entities.add({
            // 和时间轴关联
            availability: new Cesium.TimeIntervalCollection([
                new Cesium.TimeInterval({
                    start: start,
                    stop: stop
                })
            ]),
            position: property,
            // 根据所提供的速度计算模型的朝向
            orientation: new Cesium.VelocityOrientationProperty(property),
            // 模型数据
            model: {
                /*  uri:  "feiji.gltf",*/
                uri: Environment.getDataBasePath() + "/file/feiji.gltf",
                scale: 50
            },
            path: {
                resolution: 1,
                material: new Cesium.PolylineGlowMaterialProperty({
                    glowPower: 0.1,
                    color: Cesium.Color.YELLOW
                }),
                width: 10
            }
        });
    }
};

/**
 * 计算飞行
 * @param source 数据坐标
 * @returns {SampledPositionProperty|*}
 */

VisualRoamer.prototype.computeFlight = function(source) {
    // 取样位置 相当于一个集合
    let _property = new Cesium.SampledPositionProperty();
    for (let i = 0; i < source.length; i++) {
        let _time = Cesium.JulianDate.addSeconds(Cesium.JulianDate.fromDate(new Date(2020, 7, 11)), source[i].time, new Cesium.JulianDate());
        let _position = Cesium.Cartesian3.fromDegrees(source[i].longitude, source[i].latitude, source[i].height);
        // 添加位置，和时间对应
        console.log(_time, _position);
        _property.addSample(_time, _position);
    }

    return _property;
};

VisualRoamer.prototype.destroy = function() {
    let that = this;

    that._viewer.entities.removeAll();
    that._data = [];
    that._positions = [];
    that._distance = [];
    that._distance1 = [];
    that._polyline = null;

    // 起始时间
    let start = Cesium.JulianDate.fromDate(new Date(2020, 7, 11));
    // 结束时间
    let stop = Cesium.JulianDate.addSeconds(start, 360, new Cesium.JulianDate());
    that._viewer.timeline.zoomTo(start, stop);
    that._viewer.clock.currentTime = start.clone();
    that._viewer.clock.multiplier = 1;
    that._viewer.clock.shouldAnimate = false;

    // that._HANDLER.removeInputAction(Cesium.ScreenSpaceEventType.LEFT_CLICK);
};

export default VisualRoamer;
